const axios = require('axios');
const crypto = require('crypto');
const pddConfig = require('../config/pdd');

class PddService {
  constructor() {
    this.config = pddConfig;
  }

  // 生成签名
  generateSign(params) {
    // 1. 按key升序排序
    const sortedParams = Object.keys(params).sort().reduce((acc, key) => {
      acc[key] = params[key];
      return acc;
    }, {});

    // 2. 拼接字符串
    let signStr = this.config.clientSecret;
    for (let key in sortedParams) {
      signStr += key + sortedParams[key];
    }
    signStr += this.config.clientSecret;

    // 3. MD5加密转大写
    return crypto.createHash('md5').update(signStr).digest('hex').toUpperCase();
  }

  // 构建请求参数
  buildParams(type, params = {}) {
    const timestamp = Math.floor(Date.now() / 1000);
    const commonParams = {
      type,
      client_id: this.config.clientId,
      timestamp,
      data_type: 'JSON',
      version: 'v1',
      ...params
    };

    return {
      ...commonParams,
      sign: this.generateSign(commonParams)
    };
  }

  // 发送请求到拼多多API
  async request(type, params = {}) {
    try {
      const requestParams = this.buildParams(type, params);
      const response = await axios.post(this.config.api.baseUrl, null, {
        params: requestParams
      });

      if (response.data.error_response) {
        throw new Error(response.data.error_response.error_msg);
      }

      return response.data;
    } catch (error) {
      console.error('PDD API request failed:', error);
      throw error;
    }
  }

  // 解析商品ID
  extractGoodsId(command) {
    // 从口令中提取商品ID的逻辑
    const match = command.match(/[0-9]{6,}/);
    return match ? match[0] : null;
  }

  // 解析拼多多口令
  async parseCommand(command) {
    try {
      // 1. 从口令中提取商品ID
      const goodsId = this.extractGoodsId(command);
      if (!goodsId) {
        throw new Error('无法从口令中提取商品ID');
      }

      // 2. 调用拼多多商品详情API
      const response = await this.request('pdd.ddk.goods.detail', {
        goods_id_list: `[${goodsId}]`,
        pid: this.config.pid,
        custom_parameters: JSON.stringify(this.config.customParameters)
      });

      // 3. 处理返回数据
      const goodsDetail = response.goods_detail_response.goods_details[0];
      
      return {
        goods_id: goodsDetail.goods_id,
        goods_name: goodsDetail.goods_name,
        goods_thumbnail_url: goodsDetail.goods_thumbnail_url,
        min_group_price: goodsDetail.min_group_price,
        min_normal_price: goodsDetail.min_normal_price,
        mall_name: goodsDetail.mall_name,
        sales_tip: goodsDetail.sales_tip,
        mall_id: goodsDetail.mall_id
      };
    } catch (error) {
      console.error('Parse PDD command failed:', error);
      throw error;
    }
  }
}

module.exports = new PddService(); 